package com.xx.service.impl;

import com.xx.comm.util.JwtTokenUtil;
import com.xx.dto.LoginDTO;
import com.xx.entity.LoginUser;
import com.xx.entity.User;
import com.xx.mapper.UserMapper;
import com.xx.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xx.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author myx
 * @since 2024-12-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisService redisService;

    @Override
    public Map<String, String> login(LoginDTO loginDTO) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginDTO.getLoginName(),loginDTO.getPassword());
        //进行认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)){
            log.error("登陆失败");
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //将对象保存到redis中
        //将用户信息保存到redis中loginUser:用户名 --->对象
        redisService.set("loginUser"+loginUser.getUsername(),loginUser);
        //更加用户名生成token
        String token = jwtTokenUtil.generateToken(loginUser);

        Map<String,String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }
}
